import json
from django.contrib import admin
from .models import Actor, ActorDetails, Country, Company, ActorToCompany


@admin.register(Actor)
class ActorAdmin(admin.ModelAdmin):
    list_display = ('name', 'avatar', 'gender_display', 'birthday', 'country', 'score', 'create_time', 'update_time')
    list_filter = ('gender', 'country', 'score')
    search_fields = ('name', 'country__country')
    list_per_page = 20
    date_hierarchy = 'birthday'
    autocomplete_fields = ['country']
    # 添加只读字段声明
    readonly_fields = ('create_time', 'update_time')

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'avatar', 'gender', 'birthday', 'country')
        }),
        ('评分信息', {
            'fields': ('score',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('create_time', 'update_time'),
            'classes': ('collapse',)
        })
    )

    def gender_display(self, obj):
        return dict(Actor.GENDER_CHOICES).get(obj.gender, '')

    gender_display.short_description = '性别'

    def changelist_view(self, request, extra_context=None):
        # 添加演员评分分布图
        from django.db.models import Count, Case, When, IntegerField
        from django.utils.safestring import mark_safe

        score_distribution = (
            Actor.objects
            .annotate(score_group=Case(
                When(score__lte=3, then=0),
                When(score__gt=3, score__lte=6, then=1),
                When(score__gt=6, score__lte=10, then=2),
                output_field=IntegerField()
            ))
            .values('score_group')
            .annotate(count=Count('id'))
            .order_by('score_group')
        )

        chart_data = {
            'labels': ['0-3分', '4-6分', '7-10分'],
            'datasets': [{
                'data': [0, 0, 0],
                'label': '演员评分分布',
                'backgroundColor': ['#FF6384', '#36A2EB', '#FFCE56']
            }]
        }

        for item in score_distribution:
            if item['score_group'] == 0:
                chart_data['datasets'][0]['data'][0] = item['count']
            elif item['score_group'] == 1:
                chart_data['datasets'][0]['data'][1] = item['count']
            else:
                chart_data['datasets'][0]['data'][2] = item['count']

        extra_context = extra_context or {}
        extra_context['chart_data'] = mark_safe(json.dumps(chart_data))
        extra_context['chart_title'] = '演员评分分布'

        return super().changelist_view(request, extra_context=extra_context)


@admin.register(ActorDetails)
class ActorDetailsAdmin(admin.ModelAdmin):
    list_display = (
    'actor', 'roma', 'alias', 'height', 'weight', 'bust', 'hip', 'waist', 'waist', 'cups', 'hobbies', 'create_time',
    'update_time')
    search_fields = ('actor__name', 'roma', 'alias')
    autocomplete_fields = ['actor']
    list_per_page = 20

    fieldsets = (
        ('基本信息', {
            'fields': ('actor', 'roma', 'alias')
        }),
        ('身体数据', {
            'fields': ('height', 'weight', 'bust', 'hip', 'waist', 'cups'),
            'classes': ('collapse',)
        }),
        ('个人信息', {
            'fields': ('ethnicity', 'birth_place', 'blood_type', 'zodiac_sign', 'hobbies')
        }),
        ('职业信息', {
            'fields': ('debut_at', 'profile', 'experience'),
            'classes': ('collapse',)
        })
    )


@admin.register(Country)
class CountryAdmin(admin.ModelAdmin):
    list_display = ('country', 'code')
    search_fields = ('country', 'code')
    list_per_page = 30


@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    list_display = ('name', 'website')
    search_fields = ('name', 'website')
    list_per_page = 30

# @admin.register(ActorToCompany)
# class ActorToCompanyAdmin(admin.ModelAdmin):
#     list_display = ('actor', 'company', 'join_time')
#     list_filter = ('company', 'join_time')
#     search_fields = ('actor__name', 'company__name')
#     autocomplete_fields = ['actor', 'company']
#     list_per_page = 30
#     date_hierarchy = 'join_time'
